package OrderService

import (
	"context"
	"fmt"
	"gdshop-back-end-go/client-api/app/request/OrderReq"
	"gdshop-back-end-go/client-api/app/response/OrderResp"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/response"
	"github.com/gogf/gf/frame/g"
	"time"
)

// 用户支付订单
func Pay(ctx context.Context, parames *OrderReq.Pay) *response.JsonResponse {
	if !IsMyOrder(ctx, parames.Id, int(parames.MemberId)) {
		return response.FailByRequestMessage(nil, "请勿操作别人的订单")
	}

	var orderModel *OrderResp.Pay
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order").Where(
		"id=? AND member_id=?",
		parames.Id,
		parames.MemberId,
	).Struct(&orderModel)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if orderModel.Status != 1 {
		return response.FailByRequestMessage(nil, "当前订单状态不允许支付")
	}

	var paymentList []*OrderResp.PaymentList
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "payments").Where(
		"status=1").Order("sort DESC").Structs(&paymentList)

	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	// 读取当前登陆会员余额
	var memberModel *entity.Member
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member").Where("id",
		parames.MemberId).Struct(&memberModel)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	// 处理余额的备注
	for _, item := range paymentList {
		if "balance" == item.Code {
			item.Remark = "账户可用余额 ￥" +
				fmt.Sprintf("%.2f", (float64(memberModel.MoneyCoin)/float64(100)))
		}
	}
	orderModel.PaymentList = paymentList

	orderModel.CountDownSecond = g.Cfg().GetInt64("queue.CloseNoPayOrder.delayTime") - (time.Now().Unix() - orderModel.CreateAt)
	if orderModel.CountDownSecond < 1 {
		orderModel.CountDownSecond = 0
	}

	return response.SuccessByRequestMessageData(nil, "", orderModel)
}
